"use client";
import { DepositsTypes } from "@/api/depositsApi";
import { getUserRechargeApi } from "@/api/user";
import Box from "@/components/Box";
import ButtonOwn from "@/components/ButtonOwn";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { neReg } from "@/utils";
import { Form, Input, Toast } from "antd-mobile";
import { FormInstance } from "antd-mobile/es/components/form";
import { useTranslations } from "next-intl";
import { FC, Fragment, useRef, useState } from "react";

import "@/styles/deposit.scss";
interface Props {
    deposits: DepositsTypes[];
}
const DepositData: FC<Props> = (props) => {
    const { deposits } = props;
    const t = useTranslations();
    const userInfo = useUserInfoStore((state) => state.userInfo);
    const [activeType, setActiveType] = useState<DepositsTypes>(deposits[0]);

    const formInstanceRef = useRef<FormInstance>(null);
    let [amount, setAmount] = useState<number | undefined>(undefined);
    const titleChangeHandler = (item: DepositsTypes, index: number) => {
        setAmount(undefined);
        setActiveType(item);
        formInstanceRef.current?.resetFields();
    };

    const isStrictMode = true;

    const onFinish = (values: any) => {
        const params = { ...values, channel_id: activeType.id, amount: +values.amount };
        getUserRechargeApi(params)
            .then((res) => {
                formInstanceRef.current?.resetFields();
                Toast.show({ icon: "success", content: t("code.200"), maskClickable: false });
                setAmount(undefined);
                if (res.data.pay_url) {
                    window.open(res.data.pay_url);
                }
            })
            .catch((error) => {
                Toast.show({ content: t(`code${error.data.code}`), maskClickable: false });
            });
    };
    const onValuesChange = (changeValues: any) => {
        if (changeValues.amount) {
            setAmount(changeValues.amount);
        }
    };
    const amountChange = (value: number) => {
        formInstanceRef.current?.setFieldValue("amount", value);
        setAmount(value);
    };
    const amountValidator = (rules: any, value: any) => {
        if (!value) return Promise.reject(new Error(t("form.amount")));
        if (+value < activeType.min_amount)
            return Promise.reject(
                new Error(t("form.amountMinReg", { amount: activeType.min_amount }))
            );
        if (+value > activeType.max_amount)
            return Promise.reject(
                new Error(t("form.amountMaxReg", { amount: activeType.max_amount }))
            );
        return Promise.resolve();
    };
    return (
        <div className="deposit-box">
            <div className={"flex flex-wrap"}>
                {deposits.map((item, index) => {
                    return (
                        <Fragment key={item.id}>
                            <p
                                className="btn-box truncate"
                                style={{
                                    borderColor: activeType.id === item.id ? "#ff9323" : "#333",
                                }}
                                onClick={() => titleChangeHandler(item, index)}
                            >
                                {item.name}
                            </p>
                        </Fragment>
                    );
                })}
            </div>

            <Box className={"custom-form"} style={{ padding: 0 }}>
                <Form
                    style={{
                        "--border-bottom": "none",
                        "--border-top": "none",
                        "--border-inner": "none",
                    }}
                    ref={formInstanceRef}
                    footer={
                        <>
                            <ButtonOwn active>{t("DepositPage.DepositarAgora")}</ButtonOwn>
                        </>
                    }
                    initialValues={userInfo}
                    onFinish={onFinish}
                    onValuesChange={onValuesChange}
                >
                    {isStrictMode ? (
                        <>
                            <Form.Item
                                name="user_name"
                                label=""
                                rules={[{ required: true, message: t("form.usernameReg") }]}
                            >
                                <Input placeholder={t("form.username")} />
                            </Form.Item>
                            <Form.Item
                                name="passport"
                                label=""
                                rules={[
                                    { required: true, message: t("form.cardReg"), pattern: neReg },
                                ]}
                            >
                                <Input placeholder={t("form.card")} maxLength={11} type={"text"} />
                            </Form.Item>
                        </>
                    ) : null}
                    <Form.Item
                        name="amount"
                        label=""
                        rules={[{ required: true, type: "number", validator: amountValidator }]}
                    >
                        <Input
                            placeholder={`${t("DepositPage.Montante")}(BRL): Mín. ${activeType.min_amount}`}
                            type={"number"}
                            maxLength={activeType.max_amount}
                        />
                    </Form.Item>

                    <div className={"flex flex-col"}>
                        <div className={"flex-1"}>
                            <ul className="ul-box">
                                {activeType.products.map((item, index) => (
                                    <li
                                        className={amount == item.amount ? "active" : ""}
                                        key={index}
                                        onClick={() => amountChange(item.amount)}
                                    >
                                        {!!item.badge && <span className="hot"></span>}
                                        <div className="amountContent">
                                            {/* <span className="iconfont icon-unit-brl"></span> */}
                                            <span className="iconfont">R$</span>
                                            <span> {item.amount}</span>
                                        </div>
                                        <span className="amountTips">
                                            {t("DepositPage.Oferecer")} 100%
                                        </span>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                </Form>
            </Box>
        </div>
    );
};

export default DepositData;
